/* common.js */

//去掉数组里重复的项
function unique(array) {
    if (!array) return array;
    var obj = {}, a = [];
    for (var i = 0, iLen = array.length; i < iLen; i++) {
        if (!obj[array[i]]) {
            a.push(array[i]);
            obj[array[i]] = true;
        }
    }
    return a;
}

//验证表单
//isShowMessage {true,false}: 是否需要提示信息，并滚动，默认true
function isInputOK(isShowMessage) {
    var isOK = true;
    if(isShowMessage == undefined || isShowMessage == true){
        isShowMessage = true;
    }else{
        isShowMessage = false;
    }
    $('.data_confirm').each(function(index, element) {
        var wrap = $(element),
            data = wrap.attr('data-confirm');
        if (data == undefined) {
            return true;
        }
        var array_data = data.split(' ');
        wrap.val(wrap.val().trim());
        for (var i = 0; i < array_data.length; i++) {
            //必填项
            if (array_data[i] == 'required' && wrap.val() == '') {
                isOK = false;
                if (isShowMessage) {
                    wrap.addClass('error').one('focus', function() {
                        $(this).removeClass('error');
                    });
                    message('请将信息填写完整!', 'error', true, 5000);
                    $('.page_center').animate({ scrollTop: $('.page_center').scrollTop() - 100 + wrap.offset().top }, 'fast');
                }
                return false;
            }
            //选择题的选项
            if (array_data[i] == 'choice') {
                //去掉重复字母，并排序
                var formatValue = unique(wrap.val().toUpperCase().split('')).sort().join('');
                wrap.val(formatValue);

                var optionNum = wrap.parent().siblings('.optionNum').val();
                if (optionNum == undefined) return true;
                //如果答案太长
                if (formatValue.length > optionNum) {
                    isOK = false;
                    if (isShowMessage) {
                        wrap.addClass('error').one('focus', function() {
                            $(this).removeClass('error');
                        });
                        message('选择题的答案个数不能比选项个数多!', 'error', true, 5000);
                        $('.page_center').animate({ scrollTop: $('.page_center').scrollTop() - 100 + wrap.offset().top }, 'fast');
                    }
                    return false;
                }
                //如果答案有其他字母
                else if (!new RegExp('^[' + 'ABCDEFGH'.substr(0, optionNum) + ']{1,' + optionNum + '}$').test(formatValue)) {
                    isOK = false;
                    if (isShowMessage) {
                        wrap.addClass('error').one('focus', function() {
                            $(this).removeClass('error');
                        });
                        message('选择题的答案错误，请以ABC等形式输入!', 'error', true, 5000);
                        $('.page_center').animate({ scrollTop: $('.page_center').scrollTop() - 100 + wrap.offset().top }, 'fast');
                    }
                    return false;
                }

            }
            //整数
            if (array_data[i] == 'int') {
                if (!new RegExp('^\\d*$').test(wrap.val())) {
                    isOK = false;
                    if (isShowMessage) {
                        wrap.addClass('error').one('focus', function() {
                            $(this).removeClass('error');
                        });
                        message('请输入正确的数字（要求整数)', 'error', true, 5000);
                    }
                    return false;
                }
            }
            //浮点数，规定一位小数或整数的格式
            if (array_data[i] == 'float') {
                if (!new RegExp('(?:^\\d+\\.\\d$)|(?:^\\d*$)').test(wrap.val())) {
                    isOK = false;
                    if (isShowMessage) {
                        wrap.addClass('error').one('focus', function() {
                            $(this).removeClass('error');
                        });
                        message('请输入正确的数字（可有1位小数)', 'error', true, 5000);
                    }
                    return false;
                }
            }
            if (array_data[i] == 'reHTML') {
                wrap.val(replaceAllHTML(wrap.val()));
            }
        }
    });
    return isOK;
}

//替换掉特殊的HTML字符
function replaceAllHTML(txt) {
    var value = txt;
    //value = value.replace(/&/g, '&amp;');
    value = value.replace(/</g, '&lt;');
    value = value.replace(/>/g, '&gt;');
    //value = value.replace(/\"/g, '&quot;');
    //value = value.replace(/\'/g, '&#39;');
    return value;
}
/*
* message: 用来弹出提示信息
* {String} msg
* {String} msgType 消息类型 success/error
* {Boolean} isHide 是否自动隐藏
* {Number} hideTime 隐藏时间，单位毫秒
* {element} relativeElement 相对的元素，暂时不用
*/
var MESSAGE_ID_SELECTER = '#messageBox';
var timeoutID = null;

function message(msg, msgType, isHide, hideTime) {
    var messageBox = $('<div id="messageBox">' + msg + '</div>'),
        messageTop = 0,
        messageLeft = 0;
    //隐藏消息框
    hideMessage();
    //添加弹框的class
    if (msgType == 'error') {
        messageBox.addClass('errmsg');
    } else {
        messageBox.addClass('msg');
    }
    /*
    //如果有相对元素，根据相对元素的位置显示弹出框
    //否则弹在页面顶部
    relativeElement = $(relativeElement);
    if (relativeElement.length == 1) {
    //弹出消息
    var offset = relativeElement.offset();
    $('.page_container').append(messageBox);
    messageTop = offset.top - 18 - messageBox.height();
    messageLeft = offset.left;
    messageBox.css('top', messageTop);
    messageBox.css('left', messageLeft);
    } else {
    //弹出消息
    $('.page_container').append(messageBox);
    }
    */
    //弹出消息
    $('.page_container').append(messageBox);
    messageBox.fadeIn(100);
    //添加定时隐藏
    if (isHide) {
        clearTimeout(timeoutID);
        timeoutID = setTimeout(hideMessage, hideTime);
    }
}

//若存在消息框，则干掉
function hideMessage() {
    if ($(MESSAGE_ID_SELECTER).length > 0) $(MESSAGE_ID_SELECTER).remove();
}


jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

$(document).ready(function() {

    /* ============ begin_message ================*/
    var begin_message_wrap = $('#begin_message');
    var begin_message = (begin_message_wrap.length > 0) ? begin_message_wrap.val() : '';
    if (begin_message != '') {
        (begin_message.indexOf('成功') > -1) ?
            message(begin_message, 'success', true, 5000) :
            message(begin_message, 'error', true, 5000);
    }

    /*============ 文字太长，截断，换成title ================*/
    var text = $('.text_over');
    for (var i = 0; i < text.length; i++) {
        var that = $(text[i]);
        var txt = that.text();
        var num = that.attr('data-num');
        if (txt.length >= num) {
            that.attr('title', txt);
            that.text(txt.substr(0, num) + '...');
        }
    }
});